import {Modal} from 'antd-mobile';
//公用ajax
export const toAjax = {
  get: (url,params)=> {
    if (params) {
      let paramsArray = [];
      //拼接参数
      Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
      if (url.search(/\?/) === -1) {
        url += '?' + paramsArray.join('&')
      } else {
        url += '&' + paramsArray.join('&')
      }
    }
    return new Promise((resolve,reject)=>{
      fetch(url,{
        method: 'get',
        credentials: 'include',
        headers: new Headers({
            'Cache-Control': 'no-cache',
          'Access-Control-Allow-Origin': '*',
          'Content-Type': 'text/plain'
        })
      })
        .then(res => res.json())
        .then(res => {
          if(res.code === 403){
            Modal.alert('提示','您还未登录',[{text:'前往登陆',onPress: ()=> window.location.href = '/auth/goLoginPage'}])
          }else{
            resolve(res);
          }
        })
        .catch(err=>toAjax.error(err))
    });
  },
  post: (url,data)=>{
      let formData = "";
      if(data){
          if (typeof data === "object") {
              if(JSON.stringify(data) != "{}"){
                  for (let it in data) {
                      formData += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                  }
                  formData = formData.substring(0, formData.length - 1);
              }
          } else {
              formData = data;
          }
      }
    return new Promise((resolve,reject)=>{
      fetch(url, {
        method: 'POST',
        credentials: 'include',
        mode: 'cors',
          headers: {
              'Cache-Control': 'no-cache',
              'Access-Control-Allow-Origin': '*',
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          },
        body:formData
      })
        .then(res => res.json())
        .then(res => {
          if(res.code === 403){
            Modal.alert('提示','您还未登录',[{text:'前往登陆',onPress: ()=> window.location.href = '/auth/goLoginPage'}])
          }else{
            resolve(res);
          }
        })
        .catch(err=>toAjax.error(err))
    });
  },

    ajaxPost:(url,data,)=>{
        return new Promise((resolve,reject)=> {
            $.ajax({
                url: url,
                type: "POST",
                dataType: 'json',
                data: data,
                success:res=>{
                    resolve(res);
                }
            })
        })
    },
  error: (err)=>{
    console.error('Error:', err)
  }
};